package com.hzqy.service.pms;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.hzqy.web.vo.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.hzqy.commons.utils.ConstantUtils;
import com.hzqy.commons.utils.JsonUtils;
import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.commons.utils.sensitive.SensitiveMain;
import com.hzqy.persistence.dao.picture.PictureDao;
import com.hzqy.persistence.dao.pms.PmsDao;
import com.hzqy.persistence.dao.product.ProductDao;
import com.hzqy.service.core.GenericServiceBean;
import com.hzqy.service.product.ProductServiceBean;


@Service
public class PmsServiceBean extends GenericServiceBean<PmsUserVo,PmsDao, Integer>{
	private static final long serialVersionUID = 1L;
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Resource
	private PmsDao pmsDao;
	@Resource
	private PictureDao pictureDao;
	@Resource
	private ProductServiceBean productServiceBean;
	@Resource
	private ProductDao productDao;
	
	@Override
	public PmsDao getEntityDao() {
		return pmsDao;
	}

	public PmsUserVo findUser(PmsUserVo puv) {
		if(puv==null||puv.getF_pu_name()==null||puv.getF_pu_pwd()==null)
			return null;
		else
			return pmsDao.findUser(puv);
	}

	public PmsUserVo findUserByName(PmsUserVo puv) {
		if(puv==null||puv.getF_pu_name()==null)
			return null;
		else
			return pmsDao.findUserByName(puv);
	}
	
	public PmsUserVo findUserById(HttpSession session,PmsUserVo userVo,int f_pu_id) {
		PmsUserVo puv = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		userVo.setOrgId(puv.getOrgId());
		Map<String,Object> userListMap = findUserList(ConstantUtils.isSuperAdmin(puv.getRoleIds()),userVo, 1, 1000);
		ArrayList<PmsUserVo> list = (ArrayList<PmsUserVo>)userListMap.get("rows");
		int sign = 0; //0代表无权限 1代表有权限 查看用户信息
		if(list.isEmpty()){
			return null;
		}else{
			for(int i=0;i<list.size();i++){
				if(f_pu_id==list.get(i).getF_pu_id()){
					sign = 1;
				}
			}
		}
		if(f_pu_id > 0 && sign == 1) {
			int operateCounts = userVo.getOperateCounts();
			if(operateCounts == 0){
				operateCounts = 2;
			}
			userVo.setOperateCounts(operateCounts);
			LOG.debug(userVo.getF_pu_id()+"userVo="+userVo);
			userVo.setF_pu_id(f_pu_id);
			List<PmsUserVo> userOperateHistoryList = pmsDao.findUserOperatedList(userVo);
			PmsUserVo result = pmsDao.findUserById(f_pu_id);
			if(result!=null)
				result.setPmsUserOperateHistory(userOperateHistoryList);
			return result;
		} else {
			return null;
		}
	}


	
	public PmsRoleVo findRoleById(int f_prole_id) {
		if(f_prole_id <= 0) {
			return null;
		} else {
			return pmsDao.findRoleById(f_prole_id);
		}
	}
	
	public PmsAttributeVo findAttributeById(int f_pa_id) {
		if(f_pa_id <= 0) {
			return null;
		} else {
			return pmsDao.findAttributeById(f_pa_id);
		}
	}
	
	public int findUserIsExist(PmsUserVo puv) {
		if(puv==null||puv.getF_pu_name()==null||puv.getF_pu_pwd()==null)
			return -1;
		else
			return pmsDao.findUserIsExist(puv);
	}
	
	public int findRoleIsExist(PmsRoleVo prv) {
		if(prv==null||prv.getF_prole_name()==null)
			return -1;
		else
			return pmsDao.findRoleIsExist(prv);
	}
	
	/**
	 * 根据用户所属角色，得到对应资源列表
	 * @param puv
	 */
	public List<PmsResourceVo> findUserResourcesByRoleId(PmsUserVo puv) {
		List<PmsResourceVo> resourceList = null;
		resourceList = pmsDao.findUserResourcesByRoleId( puv);
		List<PmsResourceVo> parentResourceList = new ArrayList<PmsResourceVo>();
		
		int parentId = 0;
		for(Iterator<PmsResourceVo> resourceIter=resourceList.iterator();resourceIter.hasNext();) {
			PmsResourceVo prv = resourceIter.next();
			parentId = prv.getF_pr_parentId();
			if(parentId==0) {
				parentResourceList.add(prv);
				List<PmsResourceVo> childResourceList = new ArrayList<PmsResourceVo>();
				prv.setResourceList(childResourceList);
			} else {
				//将子节点存到父节点中
				for(Iterator<PmsResourceVo> parentResourceIter=parentResourceList.iterator();parentResourceIter.hasNext();) {
					PmsResourceVo parentResource = parentResourceIter.next();
					if(parentResource.getF_pr_id()==parentId)
						parentResource.getResourceList().add(prv);
				}
			}
		}
		return parentResourceList;
	}
	
	public Map<String,Object> findUserList(boolean isAdmin,PmsUserVo puv, int curPage,
			int pageSize) {
		Map<String, Object> map =new HashMap<String, Object>();
		Integer rowCount = 0;
		if(isAdmin)
			rowCount = pmsDao.findAdminUserCount(puv);
		else
			rowCount = pmsDao.findUserCount(puv);
		map.put("total", rowCount);
		if(rowCount > 0 && curPage > 0 && pageSize > 0){
			map.put("firstResult", (curPage-1)*pageSize);
			map.put("maxResults", pageSize);
			map.put("f_pu_name", puv.getF_pu_name());
			map.put("f_pu_realName", puv.getF_pu_realName());
			List<PmsUserVo> results = new ArrayList<PmsUserVo>();
			if(isAdmin) {
				results =  pmsDao.findAdminUserList(map);
			} else {
				map.put("orgId", puv.getOrgId());
				map.put("orgIds", puv.getOrgIds());
				results = pmsDao.findUserList(map);
			}
			map.put("rows", results);
		} else {
			map.put("rows", new ArrayList<PmsUserVo>());
		}
		return map;
	}
	
	public Map<String,Object> findRoleList(boolean isAdmin,int orgId,PmsRoleVo prv, int curPage,
			int pageSize) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("f_prole_name", prv.getF_prole_name());
		map.put("f_prole_status", prv.getF_prole_status());
		map.put("orgId",orgId);
		Integer rowCount = 0;
		if(isAdmin)
			rowCount = pmsDao.findAdminRoleCount(prv);
		else
			rowCount = pmsDao.findRoleCount(map);
		map.put("total", rowCount);
		if(rowCount > 0 && curPage > 0 && pageSize > 0) {
			map.put("firstResult", (curPage-1)*pageSize);
			map.put("maxResults", pageSize);
			List<PmsRoleVo> results = new ArrayList<PmsRoleVo>();
			if(isAdmin) {
				results = pmsDao.findAdminRoleList(map);
			} else {
				results = pmsDao.findRoleList(map);
			}
			map.put("rows", results);
		} else {
			map.put("rows", new ArrayList<PmsRoleVo>());
		}
		return map;
	}
	
	public Map<String,Object> findAttributeList(int f_pa_resourceId,int curPage,
			int pageSize) {
		Map<String,Object> map = new HashMap<String, Object>();
		Integer rowCount = pmsDao.findAttributeCount(f_pa_resourceId);
		map.put("total", rowCount);
		if(rowCount >0 && curPage >0 && pageSize > 0) {
			map.put("firstResult", (curPage-1)*pageSize);
			map.put("maxResults", pageSize);
			map.put("f_pa_resourceId", f_pa_resourceId);
			List<PmsAttributeVo> results = pmsDao.findAttributeList(map);
			map.put("rows", results);
		} else {
			map.put("rows",new ArrayList<PmsRoleVo>());
		}
		return map;
	}
	
	public int delUserStatus(int f_pu_id) {
		pmsDao.delUserStatus(f_pu_id);
		pmsDao.delUser(f_pu_id);
		return 1;
	}
	
	public int delRoleStatus(int f_prole_id) {
		pmsDao.delRoleStatus(f_prole_id);
		pmsDao.delRole(f_prole_id);
		return 1;
	}
	
	public int delAttributeStatus(int f_pa_id) {
		pmsDao.delRoleResourceAttByAttId(f_pa_id);
		return pmsDao.delAttributeStatus(f_pa_id);
	}
	
	public int delResourceStatus(int f_pr_id) {
		Map<String,Object> map = findAttributeList(f_pr_id,1,1000);
		int total = (Integer) map.get("total");
		if(total>0){
			return -1;
		}else{
			return pmsDao.delResourceStatus(f_pr_id);
		}
	}
	
	public int addUser(Boolean isAdmin,PmsUserVo puv) {
		int flag = 0;
		if(puv == null || puv.getF_pu_name()==null || puv.getF_pu_name().trim().length()<3 || puv.getF_pu_name().trim().length()>50) {
			flag = -1;
		} else if(puv.getF_pu_pwd() == null || puv.getF_pu_pwd().trim().length()!=32) {
			flag = -2;
		} else if(puv.getF_pu_repwd() == null) {
			flag = -3;
		} else if(puv.getF_pu_realName() == null || puv.getF_pu_realName().length()>30) {
			flag = -4;
		} else if(puv.getF_pu_sex()<0 && puv.getF_pu_sex() > 3) {
			flag = -5;
		} else if(puv.getF_pu_phone() == null || puv.getF_pu_phone().length()>15) {
			flag = -6;
		} else if(puv.getF_pu_mobile() == null || puv.getF_pu_mobile().length()>15) {
			flag = -7;
		} else if(puv.getF_pu_email() == null || puv.getF_pu_email().length()>30) {
			flag = -8;
		} else if(puv.getF_pu_address() == null || puv.getF_pu_address().length()>85) { 
			flag = -9;
		} else if(puv.getF_pu_status()<1 && puv.getF_pu_status() > 3) {
			flag = -10;
		}
		int orgId = puv.getOrgId();
		if(flag == 0) {
			pmsDao.insertUser(puv);
			int f_pu_id = puv.getF_pu_id();
			puv.setF_puh_id(f_pu_id);
			pmsDao.insertUserHistory(puv); // 新增新密码不能与前两次密码一样的功能
			if(!isAdmin) {
				PmsOrgUserVo pouv = new PmsOrgUserVo();
				pouv.setF_pou_orgId(orgId);
				pouv.setF_pou_userId(f_pu_id);
				pmsDao.insertOrgUser(pouv);
			}
			flag = 1;
		}
		return flag;
	}
	
	public int addRole(boolean isAdmin,PmsRoleVo prv,int orgId) {
		int flag = 0;
		if(prv == null || prv.getF_prole_name()==null || prv.getF_prole_name().trim().length()<3 || prv.getF_prole_name().trim().length()>50) {
			flag = -1;
		}
		if(flag == 0) {
			pmsDao.insertRole(prv);
			int f_prole_id = prv.getF_prole_id();
			if(!isAdmin) {
				PmsOrgRoleVo porv = new PmsOrgRoleVo();
				porv.setF_por_roleId(f_prole_id);
				porv.setF_por_orgId(orgId);
				pmsDao.insertOrgRole(porv);
			}
			flag = 1;
		}
		return flag;
	}
	
	public int addAttribute(PmsAttributeVo pav) {
		int flag = 0;
		if(pav == null || pav.getF_pa_name() == null || pav.getF_pa_name().trim().length() > 50) {
			flag = -1;
		}
		if(flag == 0) {
			pmsDao.insertAttribute(pav);
			flag = 1;
		}
		return flag;
	}
	
	public int updateUserPwd(PmsUserVo puv) {
			pmsDao.update(puv);
			int f_pu_id = puv.getF_pu_id();
			puv.setF_puh_id(f_pu_id);
			pmsDao.insertUserHistory(puv);
		return 1;
	}

	public int updateUser(PmsUserVo puv) {
		int flag = 0;
		if(puv == null || puv.getF_pu_name()==null || puv.getF_pu_name().trim().length()<3 || puv.getF_pu_name().trim().length()>50) {
			flag = -1;
		}  else if(puv.getF_pu_pwd() == null || puv.getF_pu_pwd().trim().length()!=32) {
			flag = -2;
		} else if(puv.getF_pu_repwd() == null) {
			flag = -3;
		} else if(puv.getF_pu_realName() == null || puv.getF_pu_realName().length()>30) {
			flag = -4;
		} else if(puv.getF_pu_sex()<0 && puv.getF_pu_sex() > 3) {
			flag = -5;
		} else if(puv.getF_pu_phone() == null || puv.getF_pu_phone().length()>15) {
			flag = -6;
		} else if(puv.getF_pu_mobile() == null || puv.getF_pu_mobile().length()>15) {
			flag = -7;
		} else if(puv.getF_pu_email() == null || puv.getF_pu_email().length()>30) {
			flag = -8;
		} else if(puv.getF_pu_address() == null || puv.getF_pu_address().length()>85) {
			flag = -9;
		} else if(puv.getF_pu_status()<1 && puv.getF_pu_status() > 3) {
			flag = -10;
		}
		if(flag == 0){
			pmsDao.update(puv);
			int f_pu_id = puv.getF_pu_id();
			puv.setF_puh_id(f_pu_id);
			pmsDao.insertUserHistory(puv); // 新增新密码不能与前两次密码一样的功能
			return 1;
		}
		return flag;
	}

	
	public int updateRole(PmsRoleVo prv) {
		int flag = 0;
		if (prv == null || prv.getF_prole_name().trim().length()<3 || prv.getF_prole_name().trim().length() >50) {
			flag = -1;
		}
		if(flag == 0) {
			pmsDao.updateRole(prv);
			return 1;
		}
		return flag;
	}
	
	public int updateAttribute(PmsAttributeVo pav) {
		int flag = 0;
		if(pav == null || pav.getF_pa_name() == null || pav.getF_pa_name().trim().length() >50) {
			flag = -1;
		} else if(pav.getF_pa_url() == null) {
			flag = -2;
		}
		if(flag == 0) {
			pmsDao.updateAttribute(pav);
			return 1;
		}
		return flag;
	}
	
	public int updateResource(PmsResourceVo prv) {
		int flag = 0;
		
		if(flag == 0) {
			pmsDao.updateResourve(prv);
			return 1;
		}
		return flag;
	}

	public List<PmsZTreeVo> selectResourceList(PmsResourceVo prv) {
		List<PmsZTreeVo> ptvList = new ArrayList<PmsZTreeVo>();
		List<PmsResourceVo> prvList = pmsDao.selectResourceList(prv);
		for(int i=0; i<prvList.size();i++){
			PmsZTreeVo ptv = new PmsZTreeVo();
			ptv.setId(prvList.get(i).getF_pr_id()+"");
			ptv.setName(prvList.get(i).getF_pr_name());
			ptv.setpId(prvList.get(i).getF_pr_parentId()+"");
			ptv.setUrl(prvList.get(i).getF_pr_url());
			ptvList.add(ptv);
		}
		return ptvList;
	}
	
	public List<PmsZTreeVo> selectOrgList(PmsUserVo puv) {
		List<PmsZTreeVo> ptvList = new ArrayList<PmsZTreeVo>();
		List<PmsOrgVo> povList = new ArrayList<PmsOrgVo>();
		if(ConstantUtils.isSuperAdmin(puv.getRoleIds())){//是超管
			povList = pmsDao.selectOrgList();//获取全部组织目录
		} else {//普通管理员
			puv.setOrgIds(this.getAuthorityPmsOrgIds(puv));
			povList = pmsDao.selectOrgByOrgId(puv);//获取有权限的组织
		}
		for(int i=0;i<povList.size();i++) {
			PmsZTreeVo ptv = new PmsZTreeVo();
			ptv.setId(povList.get(i).getF_po_id()+"");
			ptv.setName(povList.get(i).getF_po_name());
			ptv.setpId(povList.get(i).getF_po_parentId()+"");
			ptvList.add(ptv);
		}
		return ptvList;
	}

	public List<PmsOrgVo> selectOrgListByGgmodel() {
		List<PmsOrgVo> povList = pmsDao.selectOrgListByGgmodel();
		return povList;
	}
	
	public Map<String,Object> selectOrgList(PmsOrgVo pmsOrgVo,int curPage, int pageSize) {
		String address = String.format("^%s-%s-%s$", 
				StringUtils.isNotEmpty(pmsOrgVo.getF_po_address_province()) ? pmsOrgVo.getF_po_address_province() : "[0-9]{1,2}",
				StringUtils.isNotEmpty(pmsOrgVo.getF_po_address_city()) ? pmsOrgVo.getF_po_address_city() : "[0-9]{1,2}",
				StringUtils.isNotEmpty(pmsOrgVo.getF_po_address_country()) ? pmsOrgVo.getF_po_address_country() : "[0-9]{1,2}"
		);
		pmsOrgVo.setF_po_address(address);

		Map<String,Object> map = new HashMap<String, Object>();
		Integer rowCount = pmsDao.findOrgVoCount(pmsOrgVo);
		map.put("total", rowCount);
		if(rowCount > 0 && curPage > 0 && pageSize > 0) {
			map.put("firstResult", (curPage-1)*pageSize);
			map.put("maxResults", pageSize);
			map.put("f_po_name", pmsOrgVo.getF_po_name());
			map.put("f_po_id", pmsOrgVo.getF_po_id());
			map.put("f_po_parentId", pmsOrgVo.getF_po_parentId());
			map.put("f_po_status", pmsOrgVo.getF_po_status());
			map.put("orgIds", pmsOrgVo.getOrgIds());
			map.put("f_po_address", pmsOrgVo.getF_po_address());
			map.put("f_po_cdate_start", pmsOrgVo.getF_po_cdate_start());
			map.put("f_po_cdate_end", pmsOrgVo.getF_po_cdate_end());
			map.put("f_po_industry", pmsOrgVo.getF_po_industry());
			List<PmsOrgVo> results = pmsDao.findOrgVoList(map);
			map.put("rows", results);
		} else {
			map.put("rows", new ArrayList<PmsOrgVo>());
		}
		return map;
	}
	
	public PmsResourceVo selectResource(int f_pr_id) {
		PmsResourceVo prv = new PmsResourceVo();
		prv = pmsDao.selectResource(f_pr_id);
		return prv;
	}
	
	public int addResource(PmsResourceVo resourceVo) {
		int flag = 0;
		if(resourceVo==null) {
			flag = -1;
		} else if(resourceVo.getF_pr_name() == null || resourceVo.getF_pr_name().trim().length() <3 || resourceVo.getF_pr_name().trim().length() >50) {
			flag = -2;
		} else if(Integer.valueOf(resourceVo.getF_pr_parentId()) == null || resourceVo.getF_pr_parentId() <0){
			flag = -3;
		}
		if(flag == 0) {
			pmsDao.addResource(resourceVo);
			return 1;
		}
		return flag;
	}
	
	public int updateRoleResAtt(int f_prra_roleId,String attributeStr) {
		int flag = 0;
		if(f_prra_roleId <= 0) {
			flag = -1;
		} else if ("".equals(attributeStr)) {
			flag = -2;
		}
		if(flag == 0) {
			List<PmsRoleResourceAttributeVo> prraList = new ArrayList<PmsRoleResourceAttributeVo>();
			String[] strArr = attributeStr.split(";");
			for(int i=0;i<strArr.length;i++) {
				PmsRoleResourceAttributeVo prra = new PmsRoleResourceAttributeVo();
				String[] resAtt = strArr[i].split(",");
				prra.setF_prra_roleId(f_prra_roleId);
				prra.setF_prra_resourceId(Integer.valueOf(resAtt[0].replace("r", "")));
				prra.setF_prra_attributeId(Integer.valueOf(resAtt[1].replace("a", "")));
				prraList.add(prra);
			}
			
			pmsDao.deleteRoleResAtt(f_prra_roleId);
			for(int i=0;i<prraList.size();i++) {
				pmsDao.insertRoleResAtt(prraList.get(i));
			}
			return 1;
		}
		return flag;
	}
	
	public List<PmsRoleResourceAttributeVo> selectRoleAttribute(int f_prra_roleId) {
		List<PmsRoleResourceAttributeVo> prraList = new ArrayList<PmsRoleResourceAttributeVo>();
		prraList = pmsDao.selectRoleAttribute(f_prra_roleId);
		return prraList;
	}
	
	public List<PmsUserVo> selectOrgUserList() {
		List<PmsUserVo> puvList = new ArrayList<PmsUserVo>();
		puvList = pmsDao.selectOrgUserList();
		return puvList;
	}
	
	public List<PmsRoleVo> selectOrgRoleList(boolean isAdmin,int orgId) {
		List<PmsRoleVo> prvList = new ArrayList<PmsRoleVo>();
		if(isAdmin)
			prvList = pmsDao.selectOrgRoleList();
		else
			prvList = pmsDao.selectOrgRoleList(orgId);
		return prvList;
	}
	
	public Map<String,Object> addOrg(PmsOrgVo pov,String roleListValue, String userListValue,String picJson) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = 0;
		
		if(pov==null || pov.getF_po_name().trim().length()<3 || pov.getF_po_name().trim().length()>50) {
			flag = -1;
			resultMap.put("result","组织新增失败!");
		}else if("hotel".equals(SystemConfigUtils.getSysConfig("platform"))){
			List<PmsOrgVo> orgList = selectOrgByOrgName(pov.getF_po_name(),0);
			if(orgList.size()>0){
				resultMap.put("result","组织新增失败!组织名重复!");
				flag = -2;
			}
		}
		if(flag ==0) {
			Map<String, Object> name = SensitiveMain.sensitiveWordCheck(pov.getF_po_name());
			Map<String, Object> english = SensitiveMain.sensitiveWordCheck(pov.getF_po_english());
			Map<String, Object> desc = SensitiveMain.sensitiveWordCheck(pov.getF_po_desc());
			Map<String, Object> email = SensitiveMain.sensitiveWordCheck(pov.getF_po_email());
			if(!(Boolean)name.get("hasSensitiveWord")&&!(Boolean)english.get("hasSensitiveWord")&&!(Boolean)desc.get("hasSensitiveWord")&&!(Boolean)email.get("hasSensitiveWord")){
				pmsDao.insertOrg(pov);
				int f_po_id = pov.getF_po_id();
				if(f_po_id > 0) {
					if(userListValue != null && !"".equals(userListValue.trim())) {
						String[] userIds = userListValue.split(",");
						if(userIds.length>0) {
							PmsOrgUserVo pouv = new PmsOrgUserVo();
							for(int i=0;i<userIds.length;i++) {
								String userId = userIds[i];
								pouv.setF_pou_orgId(f_po_id);
								pouv.setF_pou_userId(Integer.valueOf(userId));
								pmsDao.insertOrgUser(pouv);
							}
						}
					}
					if(roleListValue != null && !"".equals(roleListValue.trim())) {
						String[] roleIds = roleListValue.split(",");
						if(roleIds.length>0) {
							PmsOrgRoleVo porv = new PmsOrgRoleVo();
							for(int i=0;i<roleIds.length;i++) {
								String roleId = roleIds[i];
								porv.setF_por_orgId(f_po_id);
								porv.setF_por_roleId(Integer.valueOf(roleId));
								pmsDao.insertOrgRole(porv);
							}
						}
					}
					if(picJson!=null&&!"".equals(picJson)){
						List<CmPicturesVo> picList = JsonUtils.jsonToPicVo(picJson);
						for(int i=0;i<picList.size();i++) {
							CmPicturesVo cmPicturesVo = new CmPicturesVo();
							cmPicturesVo = picList.get(i);
							cmPicturesVo.setF_cp_relationid(f_po_id);
							pictureDao.insertPic(cmPicturesVo);
						}
					}
					//入产品组织
					String productIds = pov.getF_cc_productid();
					if(productIds != null && !"".equals(productIds.trim())) {
						String[] productArr = productIds.split(",");
						if(productArr.length>0) {
							SysProductOrgVo spov = new SysProductOrgVo();
							for(int i=0;i<productArr.length;i++) {
								spov.setF_spo_orgid(f_po_id);
								spov.setF_spo_productid(Integer.valueOf(productArr[i]));
								productDao.insertProductOrg(spov);
							}
						}
					}
					
					String default_org_product_id = SystemConfigUtils.getSysConfig("default_org_product_id");
					if(StringUtils.isNotEmpty(default_org_product_id)) {
						productServiceBean.insertProductOrgBind(Integer.valueOf(default_org_product_id), String.valueOf(f_po_id), 1);
					}
					
					resultMap.put("success", true);
					resultMap.put("result","组织新增成功!");
				}else{
					resultMap.put("success", false);
					resultMap.put("result","组织新增失败!");
				}
			}else if((Boolean)name.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","新增组织失败!含有敏感词："+name.get("sensitiveWordSet").toString());
			}else if((Boolean)desc.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","新增组织失败!含有敏感词："+desc.get("sensitiveWordSet").toString());
			}else if((Boolean)english.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","新增组织失败!含有敏感词："+english.get("sensitiveWordSet").toString());
			}else if((Boolean)email.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","新增组织失败!含有敏感词："+email.get("sensitiveWordSet").toString());
			}
			
		}else{
			resultMap.put("success", false);
		}
		LOG.debug(resultMap.get("result")+"");
		return resultMap;
	}
	
	public PmsOrgVo selectOrg(int f_po_id) {
		PmsOrgVo pov = new PmsOrgVo();
		pov = pmsDao.selectOrg(f_po_id);
		return pov;
	}
	
	public List<PmsUserVo> selectUserOrg(int f_po_id) {
		List<PmsUserVo> puvList = new ArrayList<PmsUserVo>();
		puvList = pmsDao.selectUserOrg(f_po_id);
		return puvList;
	}
	/**
	 * 查询组织关联角色列表
	 * @param f_po_id
	 * @return
	 */
	public List<PmsRoleVo> selectRoleByOrgId(int f_po_id) {
		List<PmsRoleVo> prvList = new ArrayList<PmsRoleVo>();
		prvList = pmsDao.selectRoleByOrgId(f_po_id);
		return prvList;
	}
	
	public List<PmsOrgRoleVo> selectOrgRole(int f_po_id) {
		List<PmsOrgRoleVo> porvList = new ArrayList<PmsOrgRoleVo>();
		porvList = pmsDao.selectOrgRole(f_po_id);
		return porvList;
	}
	
	public Map<String,Object> updateOrg(PmsOrgVo pov,String roleListValue, String userListValue,String picJson,String picType) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = 0;
		if(pov==null || pov.getF_po_name().trim().length()<3 || pov.getF_po_name().trim().length()>50) {
			flag = -1;
			resultMap.put("result","组织修改失败!");
		}else if("hotel".equals(SystemConfigUtils.getSysConfig("platform"))){//酒店平台组织名不能重复
			List<PmsOrgVo> orgList = selectOrgByOrgName(pov.getF_po_name(),pov.getF_po_id());
			if(orgList.size()>0){
				resultMap.put("result","组织修改失败!组织名重复!");
				flag = -2;
			}
		}
		if(flag ==0) {
			Map<String, Object> name = SensitiveMain.sensitiveWordCheck(pov.getF_po_name());
			Map<String, Object> english = SensitiveMain.sensitiveWordCheck(pov.getF_po_english());
			Map<String, Object> desc = SensitiveMain.sensitiveWordCheck(pov.getF_po_desc());
			Map<String, Object> email = SensitiveMain.sensitiveWordCheck(pov.getF_po_email());
			if(!(Boolean)name.get("hasSensitiveWord")&&!(Boolean)english.get("hasSensitiveWord")&&!(Boolean)desc.get("hasSensitiveWord")&&!(Boolean)email.get("hasSensitiveWord")){
				pmsDao.updateOrg(pov);
				pmsDao.deleteOrgUser(pov);
				pmsDao.deleteOrgRole(pov);
				if(userListValue != null && !"".equals(userListValue.trim())) {
					String[] userIds = userListValue.split(",");
					if(userIds.length>0) {
						PmsOrgUserVo pouv = new PmsOrgUserVo();
						for(int i=0;i<userIds.length;i++) {
							String userId = userIds[i];
							pouv.setF_pou_orgId(pov.getF_po_id());
							pouv.setF_pou_userId(Integer.valueOf(userId));
							pmsDao.insertOrgUser(pouv);
						}
					}
				}
				if(roleListValue != null && !"".equals(roleListValue.trim())) {
					String[] roleIds = roleListValue.split(",");
					if(roleIds.length>0) {
						PmsOrgRoleVo porv = new PmsOrgRoleVo();
						for(int i=0;i<roleIds.length;i++) {
							String roleId = roleIds[i];
							porv.setF_por_orgId(pov.getF_po_id());
							porv.setF_por_roleId(Integer.valueOf(roleId));
							pmsDao.insertOrgRole(porv);
						}
					}
				}
				if(picJson!=null&&!"".equals(picJson)){
					List<CmPicturesVo> picList = JsonUtils.jsonToPicVo(picJson);
					String listPicId = JsonUtils.jsonToPicIdList(picJson);
					int f_cv_relationid = pov.getF_po_id();
					Map<String,Object> picMap = new HashMap<String, Object>();
					picMap.put("listPicId", listPicId);
					picMap.put("f_cp_relationid", f_cv_relationid);
					picMap.put("picType", picType);
					pictureDao.deletePic(picMap);
					for(int i=0;i<picList.size();i++) {
						CmPicturesVo cmPicturesVo = new CmPicturesVo();
						cmPicturesVo = picList.get(i);
						cmPicturesVo.setF_cp_relationid(f_cv_relationid);
						pictureDao.insertPic(cmPicturesVo);
					}
				}
				
				//入产品组织
				if("industry".equals(pov.getFlag())){
					productDao.deleteProductOrgByOrgId(pov.getF_po_id());
					String productIds = pov.getF_cc_productid();
					if(productIds != null && !"".equals(productIds.trim())) {
						String[] productArr = productIds.split(",");
						if(productArr.length>0) {
							SysProductOrgVo spov = new SysProductOrgVo();
							for(int i=0;i<productArr.length;i++) {
								spov.setF_spo_orgid(pov.getF_po_id());
								spov.setF_spo_productid(Integer.valueOf(productArr[i]));
								productDao.insertProductOrg(spov);
							}
						}
					}
				}
				
				resultMap.put("success", true);
				resultMap.put("result","组织修改成功!");
			}else if((Boolean)name.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","修改组织失败!含有敏感词："+name.get("sensitiveWordSet").toString());
			}else if((Boolean)desc.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","修改组织失败!含有敏感词："+desc.get("sensitiveWordSet").toString());
			}else if((Boolean)english.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","修改组织失败!含有敏感词："+english.get("sensitiveWordSet").toString());
			}else if((Boolean)email.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","修改组织失败!含有敏感词："+email.get("sensitiveWordSet").toString());
			}
			
		}else{
			resultMap.put("success", false);
		}
		return resultMap;
	}

	public Map<String,Object> newUpdateOrg(PmsOrgVo pov,String roleListValue, String userListValue,String picJson,String picType) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = 0;
		if(pov==null || pov.getF_po_name().trim().length()<3 || pov.getF_po_name().trim().length()>50) {
			flag = -1;
			resultMap.put("result","组织修改失败!");
		}else if("hotel".equals(SystemConfigUtils.getSysConfig("platform"))){//酒店平台组织名不能重复
			List<PmsOrgVo> orgList = selectOrgByOrgName(pov.getF_po_name(),pov.getF_po_id());
			if(orgList.size()>0){
				resultMap.put("result","组织修改失败!组织名重复!");
				flag = -2;
			}
		}
		if(flag ==0) {
			Map<String, Object> name = SensitiveMain.sensitiveWordCheck(pov.getF_po_name());
			Map<String, Object> english = SensitiveMain.sensitiveWordCheck(pov.getF_po_english());
			Map<String, Object> desc = SensitiveMain.sensitiveWordCheck(pov.getF_po_desc());
			Map<String, Object> email = SensitiveMain.sensitiveWordCheck(pov.getF_po_email());
			if(!(Boolean)name.get("hasSensitiveWord")&&!(Boolean)english.get("hasSensitiveWord")&&!(Boolean)desc.get("hasSensitiveWord")&&!(Boolean)email.get("hasSensitiveWord")){
				pmsDao.updateOrg(pov);
				//pmsDao.deleteOrgUser(pov);
				//pmsDao.deleteOrgRole(pov);
				/*if(roleListValue != null && !"".equals(roleListValue.trim())) {
					String[] roleIds = roleListValue.split(",");
					if(roleIds.length>0) {
						PmsOrgRoleVo porv = new PmsOrgRoleVo();
						for(int i=0;i<roleIds.length;i++) {
							String roleId = roleIds[i];
							porv.setF_por_orgId(pov.getF_po_id());
							porv.setF_por_roleId(Integer.valueOf(roleId));
							pmsDao.insertOrgRole(porv);
						}
					}
				}*/
				if(picJson!=null&&!"".equals(picJson)){
					List<CmPicturesVo> picList = JsonUtils.jsonToPicVo(picJson);
					String listPicId = JsonUtils.jsonToPicIdList(picJson);
					int f_cv_relationid = pov.getF_po_id();
					Map<String,Object> picMap = new HashMap<String, Object>();
					picMap.put("listPicId", listPicId);
					picMap.put("f_cp_relationid", f_cv_relationid);
					picMap.put("picType", picType);
					pictureDao.deletePic(picMap);
					for(int i=0;i<picList.size();i++) {
						CmPicturesVo cmPicturesVo = new CmPicturesVo();
						cmPicturesVo = picList.get(i);
						cmPicturesVo.setF_cp_relationid(f_cv_relationid);
						pictureDao.insertPic(cmPicturesVo);
					}
				}

				//入产品组织
				if("industry".equals(pov.getFlag())){
					productDao.deleteProductOrgByOrgId(pov.getF_po_id());
					String productIds = pov.getF_cc_productid();
					if(productIds != null && !"".equals(productIds.trim())) {
						String[] productArr = productIds.split(",");
						if(productArr.length>0) {
							SysProductOrgVo spov = new SysProductOrgVo();
							for(int i=0;i<productArr.length;i++) {
								spov.setF_spo_orgid(pov.getF_po_id());
								spov.setF_spo_productid(Integer.valueOf(productArr[i]));
								productDao.insertProductOrg(spov);
							}
						}
					}
				}

				resultMap.put("success", true);
				resultMap.put("result","组织修改成功!");
			}else if((Boolean)name.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","修改组织失败!含有敏感词："+name.get("sensitiveWordSet").toString());
			}else if((Boolean)desc.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","修改组织失败!含有敏感词："+desc.get("sensitiveWordSet").toString());
			}else if((Boolean)english.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","修改组织失败!含有敏感词："+english.get("sensitiveWordSet").toString());
			}else if((Boolean)email.get("hasSensitiveWord")){
				resultMap.put("success", false);
				resultMap.put("result","修改组织失败!含有敏感词："+email.get("sensitiveWordSet").toString());
			}

		}else{
			resultMap.put("success", false);
		}
		return resultMap;
	}

	public List<PmsOrgUserRoleVo> selectOrgUserRole(int f_po_id) {
		List<PmsOrgUserRoleVo> pourvList = new ArrayList<PmsOrgUserRoleVo>();
		pourvList = pmsDao.selectOrgUserRole(f_po_id);
		return pourvList;
	}
	
	public int addOrgUserRole(int f_po_id,String userRightValue) {
		int flag = 0;
		if(f_po_id <= 0) {
			flag = -1;
		}
		if(flag == 0) {
			pmsDao.deleteOrgUserRole(f_po_id);
			if(userRightValue != null && !"".equals(userRightValue.trim())) {
				String[] userRoles = userRightValue.split(";");
				for(int i=0;i<userRoles.length;i++) {
					String[] userRole = userRoles[i].split(",");
					PmsOrgUserRoleVo pourv = new PmsOrgUserRoleVo();
					pourv.setF_pour_orgId(f_po_id);
					pourv.setF_pour_userId(Integer.valueOf(userRole[0]));
					pourv.setF_pour_roleId(Integer.valueOf(userRole[1]));
					pmsDao.insertOrgUserRole(pourv);
				}
			}
			return 1;
		}
		return flag;
	}
	
	public int deleteOrg(int f_po_id) {
		int flag = 0;
		if(f_po_id <=0) {
			flag = -1;
		}
		if(flag == 0) {
			PmsOrgVo pov = new PmsOrgVo();
			pov.setF_po_id(f_po_id);
			pmsDao.deleteOrg(f_po_id);
			pmsDao.deleteOrgUser(pov);
			pmsDao.deleteOrgRole(pov);
			pmsDao.deleteOrgUserRole(f_po_id);
			return 1;
		}
		return flag;
	}
	
	public List<PmsAttributeVo> selectAttributeList(PmsUserVo puv) {
		return pmsDao.selectUserAttributeList( puv);
	}
	
	public List<PmsResourceVo> selectUserResourceList(PmsUserVo puv) {
		return pmsDao.selectUserResourceList( puv);
	}
	
	public boolean checkOldPwd(PmsUserVo userVo,String oldPwd) {
		PmsUserVo puv = pmsDao.selectPwdById(userVo);
		if(puv.getF_pu_pwd().equals(oldPwd)) {
			return true;
		}
		return false;
	}
	
	public int updatePassword(PmsUserVo puv) {
		int flag = 0;
		if(puv==null || puv.getF_pu_pwd() == null) {
			flag = -1;
		}
		if(flag == 0) {
			pmsDao.updatePassword(puv);
			return 1;
		}
			
		return flag;
	}
	
	public List<PmsResourceVo> selectAllResource() {
		List<PmsResourceVo> resourceList = new ArrayList<PmsResourceVo>();
		resourceList = pmsDao.selectAllResource();
		return resourceList;
	}
	
	public List<PmsAttributeVo> selectAllAttribute() {
		List<PmsAttributeVo> attList = new ArrayList<PmsAttributeVo>();
		attList = pmsDao.selectAllAttribute();
		return attList;
	}
	
	public Map<String,Object> selectOrgListByParentId(PmsUserVo sessionUserVo, PmsOrgVo pmsOrgVo,int curPage, int pageSize) {
		Map<String,Object> map = new HashMap<String, Object>();
		String authorityOrgIds = this.getAuthorityPmsOrgIds(sessionUserVo);
		pmsOrgVo.setOrgIds(authorityOrgIds);
		Integer rowCount = pmsDao.findOrgCount(pmsOrgVo);
		map.put("total", rowCount);
		if(rowCount > 0 && curPage > 0 && pageSize > 0) {
			map.put("firstResult", (curPage-1)*pageSize);
			map.put("maxResults", pageSize);
			map.put("orgIds", authorityOrgIds);
			map.put("f_po_name", pmsOrgVo.getF_po_name());
			map.put("f_po_status", pmsOrgVo.getF_po_status());
			map.put("f_po_parentId", pmsOrgVo.getF_po_parentId());
			List<PmsOrgVo> results = pmsDao.selectOrgListByParentId(map);
			map.put("rows", results);
		} else {
			map.put("rows", new ArrayList<PmsOrgVo>());
		}
		return map;
	}
	
	public int updateOrgStatus(int f_po_id,int f_po_status) {
		int flag = 0;
		flag = pmsDao.updateOrgStatus(f_po_id,f_po_status);
		return flag;
	}
	
	
	/**
	 * 获取当前用户有权限看的组织id列表 用","隔开 通用
	 */
	public String getAuthorityPmsOrgIds(PmsUserVo sessionUserVo) {
		List<PmsOrgVo> authorityOrgList = this.getAuthorityPmsOrgs(sessionUserVo.getOrgId());
		String orgIds = "";
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < authorityOrgList.size(); i ++) {
			sb.append(authorityOrgList.get(i).getF_po_id());
			sb.append(",");
			//orgIds += authorityOrgList.get(i).getF_po_id() + ",";
		}
		sb.append(sessionUserVo.getOrgId());
		orgIds = sb.toString();
		return orgIds;
	}
	
	/**
	 * 获取当前用户有权限看的组织id列表 用","隔开
	 * 行业专用，过滤id <= 216的所有组织
	 */
	public String getIndustryAuthorityPmsOrgIds(PmsUserVo sessionUserVo) {
		List<PmsOrgVo> authorityOrgList = this.getAuthorityPmsOrgs(sessionUserVo.getOrgId());
		String orgIds = "";
		for(int i = 0; i < authorityOrgList.size(); i ++) {
			if(authorityOrgList.get(i).getF_po_id() > 216) {
				orgIds += authorityOrgList.get(i).getF_po_id() + ",";
			}
		}
		
		if(sessionUserVo.getOrgId() > 216) {
			orgIds += sessionUserVo.getOrgId();//本身组织加入
		} else {
			orgIds += 0;
		}
		return orgIds;
	}
	
	/**
	 * 获取当前用户有权限看的组织列表
	 */
	public List<PmsOrgVo> getAuthorityPmsOrgs(int parentOrgId) {
		List<PmsOrgVo> allOrgList = new ArrayList<PmsOrgVo>();
		List<PmsOrgVo> secondOrgListAll = new ArrayList<PmsOrgVo>();
		List<PmsOrgVo> subOrgList = pmsDao.selectAuthorityOrgListByParentId(parentOrgId);
		
		if(subOrgList.size() > 0) {
			for(int i = 0; i < subOrgList.size(); i ++) {
				PmsOrgVo orgVo = subOrgList.get(i);
				if(orgVo.getSubOrgIds() != null && orgVo.getSubOrgIds().length() > 0) {
					List<PmsOrgVo> secondSubOrgList = getAuthorityPmsOrgs(orgVo.getF_po_id());
					secondOrgListAll.addAll(secondSubOrgList);
				}
			}
		}
		
		allOrgList.addAll(subOrgList);
		allOrgList.addAll(secondOrgListAll);
		return allOrgList;
	}

	public Map<String, Object> openVistualChannel(PmsOrgVo pmsOrgVo) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int flag = pmsDao.openVistualChannel(pmsOrgVo);
		resultMap.put("flag", flag);
		return resultMap;
	}

	public Map<String, Object> updateVistualStatus(PmsOrgVo pmsOrgVo) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int flag = pmsDao.updateVistualStatus(pmsOrgVo);
		resultMap.put("flag", flag);
		return resultMap;
	}
	
	/**
	 * 根据f_clo_orgid 查询 绑定的目录
	 * @param f_clo_orgid
	 * @return
	 */
	public List<CmLabelOrgVo> selectLabelBind(int f_clo_orgid) {
		return pmsDao.selectLabelBind(f_clo_orgid);
	}
	
	/**
	 * 修改组织绑定的标签目录
	 * @param f_clo_orgid
	 * @param labelStr
	 * @param labeldeStr
	 * @return
	 */
	public int updateLabelBind(int f_clo_orgid,String labelStr,String labeldeStr, HttpSession session) {
		PmsUserVo userVo = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		int flag = 0;
		if(f_clo_orgid <= 0) {
			flag = -1;
		} else if ((labelStr == null || labelStr.equals("")) && (labeldeStr == null || labeldeStr.equals(""))) {
			flag = -2;
		}
		if(userVo.getParentOrgId()>0){
			List<PmsOrgVo> authorityOrgList = this.getAuthorityPmsOrgs(userVo.getOrgId());
			boolean b  = false;
			for(int i = 0; i < authorityOrgList.size(); i ++) {
				if(authorityOrgList.get(i).getF_po_id() == f_clo_orgid) {
					b = true;
					break;
				}
			}
			if(!b){
				flag = -5;
			}
		}
		
		if(flag == 0) {
			flag = 1;
			if(labeldeStr != null &&!labeldeStr.equals("")){
				String[] delabelIds = labeldeStr.split(",");
				for(String str:delabelIds) {
					int f_clo_labelid = Integer.valueOf(str);
					CmLabelOrgVo cmLabelOrgVo = new CmLabelOrgVo();
					cmLabelOrgVo.setF_clo_labelid(f_clo_labelid);
					cmLabelOrgVo.setF_clo_orgid(f_clo_orgid);
					pmsDao.deleteLabelBind(cmLabelOrgVo);
				}
			}
			
			if(labelStr != null &&!labelStr.equals("")){
				String[] inlabelIds = labelStr.split(","); 
				for(String str:inlabelIds) {
					int f_clo_labelid = Integer.valueOf(str);
					CmLabelOrgVo cmLabelOrgVo = new CmLabelOrgVo();
					cmLabelOrgVo.setF_clo_labelid(f_clo_labelid);
					cmLabelOrgVo.setF_clo_orgid(f_clo_orgid);
					pmsDao.insertLabelBind(cmLabelOrgVo);
				}
			}
		}
		return flag;
	}
	
	public List<PmsOrgVo> selectOrgByOrgName(String f_po_name,int f_po_id){
		List<PmsOrgVo> list = pmsDao.selectOrgByOrgName(f_po_name,f_po_id);
		return list;
	}
	
	public List<PmsZTreeVo> selectProductList() {
		List<PmsZTreeVo> ptvList = new ArrayList<PmsZTreeVo>();
		List<SysProductVo> povList = new ArrayList<SysProductVo>();
		povList = pmsDao.selectProductList();
		for(int i=0;i<povList.size();i++) {
			PmsZTreeVo ptv = new PmsZTreeVo();
			ptv.setId(povList.get(i).getF_sp_id()+"");
			ptv.setName(povList.get(i).getF_sp_name());
			ptv.setpId(povList.get(i).getF_sp_parentid()+"");
			ptvList.add(ptv);
		}
		return ptvList;
	}
	public List<String> selectWords() {

		return pmsDao.selectWords();

	}

	public int findUserHistoryPWdCount(PmsUserVo userVo){
		return pmsDao.findUserHistoryPWdCount(userVo);
	}
	public PmsUserVo findLastUserHistoryPwd(PmsUserVo userVo){
		return pmsDao.findLastUserHistoryPwd(userVo);
	}

	public int updateUserStatus(PmsUserVo userVo){
		return pmsDao.updateUserStatus(userVo);
	}



}
